package selef.xiafan.shiro.config;

import org.apache.shiro.authc.credential.HashedCredentialsMatcher;
import org.apache.shiro.codec.Base64;
import org.apache.shiro.mgt.SecurityManager;
import org.apache.shiro.spring.LifecycleBeanPostProcessor;
import org.apache.shiro.spring.security.interceptor.AuthorizationAttributeSourceAdvisor;
import org.apache.shiro.spring.web.ShiroFilterFactoryBean;
import org.apache.shiro.web.mgt.CookieRememberMeManager;
import org.apache.shiro.web.mgt.DefaultWebSecurityManager;
import org.apache.shiro.web.servlet.SimpleCookie;
import org.apache.shiro.web.session.mgt.DefaultWebSessionManager;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import selef.xiafan.shiro.realm.MyRealm;
import selef.xiafan.shiro.filter.ShiroUrlMathFilter;

import javax.servlet.Filter;
import java.util.HashMap;
import java.util.LinkedHashMap;


/**
 * @Bean: 将该方法作为配置文件
 */

@Configuration
public class ShiroConfiguration {
    @Bean
    public static LifecycleBeanPostProcessor lifecycle() {
        return new LifecycleBeanPostProcessor();
    }

    // 登录拦截--过滤器配置
    @Bean
    public ShiroFilterFactoryBean shiroFilterFactoryBean(SecurityManager securityManager) {
        ShiroFilterFactoryBean shiroFilterFactoryBean = new ShiroFilterFactoryBean();
        // 引入Shiro的控制中心---安全管理器
        shiroFilterFactoryBean.setSecurityManager(securityManager);
        LinkedHashMap<String, String> filterMap = new LinkedHashMap<>();
        HashMap<String, Filter> customizedFilter = new HashMap<>();
        customizedFilter.put("url", getURLPathMatchingFilter());
        filterMap.put("/api/system/**","url");
//        filterMap.put("/api/customer/**","url");
        // 启动过滤器
        shiroFilterFactoryBean.setFilters(customizedFilter);
        filterMap.put("/api/authentication","authc");
        shiroFilterFactoryBean.setFilterChainDefinitionMap(filterMap);
        return shiroFilterFactoryBean;
    }

    public ShiroUrlMathFilter getURLPathMatchingFilter() {
        return new ShiroUrlMathFilter();
    }


    /*
     *  安全管理配置       SecurityManager是一个接口，只有使用实现类来通过new的方式使用
     *  通过Realm获取到用户的安全数据，如用户：用来验证身份
     *                         角色或权限：用来验证用户是否能进行操作
     */
    @Bean
    public SecurityManager securityManager(MyRealm myRealm) {
        DefaultWebSecurityManager securityManager = new DefaultWebSecurityManager();
        securityManager.setRealm(myRealm);
//        securityManager.setSessionManager(defaultWebSessionManger());
        return securityManager;
    }

    @Bean
    public CookieRememberMeManager rememberMeManager() {
        CookieRememberMeManager cookieRememberMeManager = new CookieRememberMeManager();
        SimpleCookie simpleCookie = new SimpleCookie("rememberMe");
        simpleCookie.setMaxAge(259200);
        cookieRememberMeManager.setCookie(simpleCookie);
        cookieRememberMeManager.setCipherKey("EVANNIGHTLY_WAOU".getBytes());
//        cookieRememberMeManager.setCipherKey(Base64.decode("6ZmI6I2j5Y+R5aSn5ZOlAA==")); // 不能使用自定义的session值，会导致后续使用获取不到认证信息
        return cookieRememberMeManager;
    }

    /*
     * 对session进行配置，设置超时时间等
     */
//    @Bean
//    public DefaultWebSessionManager defaultWebSessionManger() {
//        DefaultWebSessionManager sessionManager = new DefaultWebSessionManager();
//        sessionManager.setGlobalSessionTimeout(100000);
//        sessionManager.setDeleteInvalidSessions(true);
//        sessionManager.setSessionValidationSchedulerEnabled(true);
//        sessionManager.setDeleteInvalidSessions(true);
////        sessionManager.setSessionIdCookie(getSessionIdCookie()); // 防止因为session污染
//        return sessionManager;
//    }

    /**
     * 自定义认证配置
     */
    @Bean
    public MyRealm myRealm() {
        MyRealm myRealm = new MyRealm();
        // 设置密码比较器
        myRealm.setCredentialsMatcher(hashedCredentialsMatcher());
        return myRealm;
    }

    /**
     * 加密方式配置
     *
     * @return 加工后的密码
     */
    @Bean
    public HashedCredentialsMatcher hashedCredentialsMatcher() {
        HashedCredentialsMatcher hashedCredentialsMatcher = new HashedCredentialsMatcher();
        // 使用md5算法进行加密      Use md 5 algorithm for encryption
        hashedCredentialsMatcher.setHashAlgorithmName("md5");
        // 设置加密次数       Set encryption times
        hashedCredentialsMatcher.setHashIterations(2);
        return hashedCredentialsMatcher;
    }

    @Bean
    public AuthorizationAttributeSourceAdvisor authorizationAttributeSourceAdvisor(SecurityManager securityManager) {
        AuthorizationAttributeSourceAdvisor authorizationAttributeSourceAdvisor = new AuthorizationAttributeSourceAdvisor();
        authorizationAttributeSourceAdvisor.setSecurityManager(securityManager);
        return authorizationAttributeSourceAdvisor;
    }

}
